package com.example.woke;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.woke1.FriendborrowActivity;
import com.zhongcai.online.R;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.woke.method.Intentnet;
import com.woke.method.MyApp;
import com.woke.uiviewpay.DateTimePickDialogUtil;
import com.wokeMy.view.turui.MyRealNameActivity;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class BorrowActivity extends Activity implements OnClickListener {

	private TextView mTtowhy;
	private TextView mTpaytime;
	private TextView mTok;
	private CheckBox mBox;
	private EditText mEbdays,mEblili;
	private TextView mTbmoney;
//	private Dialog dialog;
	private View timePicker1;
	private Intent intent = new Intent();
	private MyApp myapp;
//	private boolean textline = false;//�ж�С���λ���Ƿ񳬹�
	private AlertDialog alertDialog;
	private String initEndDateTime = "2015年12月23日 17:44"; // ��ʼ������ʱ��
	private ArrayList<String> photolist;
	private View layout_log;
	private Dialog dialog;
	private WebView mWebView;
	ArrayList<String> list = new ArrayList<String>();
	private float allmoney;
	private float lili;
	private String time;
	private String forwhy;
	private int adays;
	private RelativeLayout mFrame;
	private ArrayList<String> stringExtra = new ArrayList<String>();//ָ���ĺ���id
	private TextView mTfriend;
	private String useridlist = "" ;//ָ������id�ַ��࣬�������
	private Intentnet net;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_borrow);
		
		net = new Intentnet();
		initEndDateTime = Intentnet.getcurrenttime1() + "12:00";
		Log.e("strTime1", "+"+initEndDateTime);
		myapp = (MyApp) getApplication();
		intview();
	}

	private void intview() {
		layout_log = getLayoutInflater().inflate(R.layout.xieyi_layout, null);
		mWebView = (WebView) layout_log.findViewById(R.id.webView1);
		mEbdays = (EditText) findViewById(R.id.avborrow_edit_bdays);
		mEblili = (EditText) findViewById(R.id.avborrow_edit_blili);
		mTbmoney = (TextView) findViewById(R.id.avborrow_text_bmoney);
		findViewById(R.id.avborrow_image_back).setOnClickListener(this);
		mTtowhy = (TextView) findViewById(R.id.avborrow_text_towhy);
		mTtowhy.setOnClickListener(this);
		mTpaytime = (TextView) findViewById(R.id.avborrow_text_paytime);
		mTpaytime.setOnClickListener(this);
		findViewById(R.id.avborrow_red_text).setOnClickListener(this);//���Э��
		mTok = (TextView) findViewById(R.id.avborrow_text_ok);
		mFrame = (RelativeLayout) findViewById(R.id.avborosse_frame_show);//��
		mTfriend = (TextView) findViewById(R.id.avborrow_text_friends);
		mTfriend.setOnClickListener(this);
		mBox = (CheckBox) findViewById(R.id.avborrow_check_box);
		mBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightred));
					mTok.setClickable(true);
				}else{
					mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightgray));
					mTok.setClickable(false);
				}
			}
		});
		mTok.setOnClickListener(this);
		mTok.setClickable(false);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == 401){
			if(resultCode == 302){
				photolist = data.getStringArrayListExtra("photolist");
				String fortype = data.getStringExtra("fortype");
				Log.e("data", ""+photolist);
//				photolist = data.getStringArrayListExtra("photolist");
				mTtowhy.setText(fortype);
			}
		}else if(requestCode == 402){
			if(resultCode == 403){
				stringExtra = data.getStringArrayListExtra("datalist");
				if(stringExtra.size() > 0){
					mTfriend.setText("已添加"+stringExtra.size()+"个好友");
					useridlist = ""+stringExtra;
					useridlist = (String) useridlist.subSequence(1, useridlist.length() - 1);
				}else{
					mTfriend.setText("全部好友");
					useridlist = "";
				}
				Log.e("useridlist", "***"+useridlist);
			}
		}
	}
	
	private void getparams() {
		String tmoney = mTbmoney.getText().toString().trim();
		boolean textline = false;//�ж�С���λ���Ƿ񳬹�
		int indexOf = tmoney.indexOf('.');
		int length = tmoney.length();
		if(indexOf > -1){
			if((length-indexOf - 1) > 2){
				textline = true;
			}
		}
		
		String tlili = mEblili.getText().toString().trim();
		boolean textline1 = false;//�ж�С���λ���Ƿ񳬹�
		int indexOf1 = tlili.indexOf('.');
		int length1 = tlili.length();
		if(indexOf1 > -1){
			if((length1-indexOf1 - 1) > 2){
				textline1 = true;
			}
		}
		float parseInt = 0;
		if(!tlili.equals("")){
			 parseInt = Float.parseFloat(tlili);
		}
		forwhy = mTtowhy.getText().toString().trim();
		time = mTpaytime.getText().toString().trim();
		int getcurrenttime = net.getcurrenttime();
//		Log.e("getcurrenttime", "1"+getcurrenttime);
		boolean timepset = false;
		if(null == time || time.equals("")){
//			Log.e("##", "$$");
		}else{
			String time2 = Intentnet.getTime(time);
			int parseInt2 = Integer.parseInt(time2);
//			Log.e("L"+parseInt2, "L"+getcurrenttime);
			if((parseInt2 - getcurrenttime) > 0){
				timepset = true;
			}else{
				timepset = false;
			}
		}
		String days = mEbdays.getText().toString().trim();
//		Log.e("myapp.gettruename()", ""+myapp.gettruename());
		if(tmoney.equals("") || null == tmoney){
			Toast.makeText(BorrowActivity.this, "金额不能为空", Toast.LENGTH_SHORT).show();
		}else if(!tmoney.equals("") && null != tmoney && Integer.parseInt(tmoney) > 100000){
			Toast.makeText(BorrowActivity.this, "最大借款额不超过100000元", Toast.LENGTH_SHORT).show();
		}else if(textline == true){
			Toast.makeText(BorrowActivity.this, "金额小数点后最多2位", Toast.LENGTH_SHORT).show();
		}else if(tlili.equals("") || null == tlili){
			Toast.makeText(BorrowActivity.this, "利率不能为空", Toast.LENGTH_SHORT).show();
		}else if(textline1 == true){
			Toast.makeText(BorrowActivity.this, "利率小数点后最多2位", Toast.LENGTH_SHORT).show();
		}else if(parseInt > 100){
			Toast.makeText(BorrowActivity.this, "利率不能超过100%", Toast.LENGTH_SHORT).show();
		}else if(forwhy.equals("") || null == forwhy){
			Toast.makeText(BorrowActivity.this, "借款用途不能为空", Toast.LENGTH_SHORT).show();
		}else if(time.equals("") || null == time){
			Toast.makeText(BorrowActivity.this, "还款时间不能为空", Toast.LENGTH_SHORT).show();
		}else if(days.equals("") || null == days){
			Toast.makeText(BorrowActivity.this, "此单有效时间不能为空", Toast.LENGTH_SHORT).show();
		}
		else if(timepset == false){
			Toast.makeText(BorrowActivity.this, "还款日期应大于当前日期", Toast.LENGTH_SHORT).show();
		}
		else{
			allmoney = Float.parseFloat(tmoney);
			lili = Float.parseFloat(tlili);
			adays = Integer.valueOf(days).intValue();
			if(adays > 30){
				Toast.makeText(BorrowActivity.this, "有效时间不能超过30天", Toast.LENGTH_SHORT).show();
			}else{
				if(myapp.getDatas_load ()==null){
					aralogid("还未登录","前往登录？",1);
					return;
				}
				if(null == myapp.getDatas_load().getId()){
//					Toast.makeText(BorrowActivity.this, "��δ��¼", Toast.LENGTH_SHORT).show();
					aralogid("还未登录","前往登录？",1);
					
				}
				else if(!myapp.getDatas_load().getUser_no_status().equals("3")){
					aralogid("还未实名认证","前往认证？",2);
					Toast.makeText(BorrowActivity.this, "还未实名认证", Toast.LENGTH_SHORT).show();
				}
				else{
					getservice();
//					intent.setClass(BorrowActivity.this, BorrowsureActivity.class);
//					intent.putExtra("allmoney", allmoney);
//					intent.putExtra("lili", lili);
//					intent.putExtra("atime", time);
//					intent.putExtra("forwhy", forwhy);
//					intent.putExtra("adays", adays);
//					intent.putExtra("photolist", photolist);
//					startActivity(intent);
				}
			}
		}
	}
	
	
	private void getservice() {
		AsyncHttpClient ahc = new AsyncHttpClient();
		PersistentCookieStore myCookieStore = new PersistentCookieStore(BorrowActivity.this);    
        ahc.setCookieStore(myCookieStore); 
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "quota");
		params.put("a", "getQuotafee");
		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				Log.e("response", "ddd"+response);
//				{"data":{"data":"50"},"time":1452154562,"info":"�����ɹ�","flag":"success"}
				try {
					String flag = response.getString("flag");
					if(flag.equals("success")){
						JSONObject jsonObject = response.getJSONObject("data");
						String servifee = jsonObject.getString("data");
						float parseFloat = Float.parseFloat(servifee);
						int parseInt = Integer.parseInt(servifee);
						intent.setClass(BorrowActivity.this, BorrowsureActivity.class);
						intent.putExtra("allmoney", allmoney);
						intent.putExtra("lili", lili);
						intent.putExtra("atime", time);
						intent.putExtra("forwhy", forwhy);
						intent.putExtra("adays", adays);
						intent.putExtra("parseInt", parseInt);//����
						intent.putExtra("parseFloat", allmoney-parseFloat);//ʵ�ʵ���
						intent.putExtra("photolist", photolist);
						intent.putExtra("stringExtra", useridlist);
						startActivity(intent);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
				Toast.makeText(BorrowActivity.this, "发布失败！", Toast.LENGTH_SHORT).show();
//				Log.e("response", "ʧ��"+responseString);
			}
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				mFrame.setVisibility(View.VISIBLE);
				mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightgray));
//				mRelativ.setVisibility(View.VISIBLE);
			}
			
			@Override
			public void onFinish() {
				super.onFinish();
//				mRelativ.setVisibility(View.GONE);
				mFrame.setVisibility(View.GONE);
				mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightred));
//				Log.e("response", "���");
			}
		});
	}

	private void aralogid(String info,String kll,final int ppp){
		   alertDialog = new AlertDialog.Builder(this). 
	                setTitle(info). 
	                setMessage(kll). 
//	                setIcon(R.drawable.ic_launcher). 
	                setPositiveButton("确定", new DialogInterface.OnClickListener() { 
	                    @Override 
	                    public void onClick(DialogInterface dialog, int which) { 
//	                    Intent intent = new Intent();
	                    	if(ppp == 1){
	                    		intent.setClass(BorrowActivity.this, LoadActivity.class);
	                    		startActivity(intent);
	                    	}else if(ppp == 2){
	                    		intent.setClass(BorrowActivity.this, MyRealNameActivity.class);
	                    		startActivity(intent);
	                    	}
	                    	alertDialog.dismiss();
	                    } 
	                }). 
	                setNegativeButton("取消", new DialogInterface.OnClickListener() { 
	                    @Override 
	                    public void onClick(DialogInterface dialog, int which) { 
	                    	alertDialog.dismiss();
	                        // TODO Auto-generated method stub  
	                    } 
	                }).create(); 
	        alertDialog.show(); 
	}

	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.avborrow_text_towhy:
			intent.setClass(BorrowActivity.this, BorrowforActivity.class);
//			intent.setClass(BorrowActivity.this, UploadfileActivity.class);
			startActivityForResult(intent, 401);
			break;
			
		case R.id.avborrow_text_friends:
		intent.setClass(BorrowActivity.this, FriendborrowActivity.class);
//		intent.setClass(BorrowActivity.this, UploadfileActivity.class);
		intent.putExtra("chenckedf", stringExtra);//��ѡ������
		startActivityForResult(intent, 402);
		break;
			
		case R.id.avborrow_text_paytime:
			
			DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
					BorrowActivity.this, initEndDateTime);
			dateTimePicKDialog.dateTimePicKDialog(mTpaytime);
			break;
			
		case R.id.avborrow_text_ok:
			getparams();
			break;
			
		case R.id.avborrow_red_text:
			String lili = ""+mEblili.getText().toString().trim();
			String money = ""+mTbmoney.getText().toString().trim();
			String day = ""+mTpaytime.getText().toString().trim();
			Intentnet net = new Intentnet();
			String strTime = "";
			if(day.equals("")){
				strTime = day;
			}else{
				 strTime = Intentnet.getTime(day);
			}
//			xieyidata(lili,money,day);
			ArrayList<String> list = new ArrayList<String>();
			list.add(lili);
			list.add(money);
			list.add(strTime);
			Intent intent = new Intent(BorrowActivity.this,YuqiActivity.class);
			intent.putExtra("list", list);
//			Log.e("list", "list"+list);
			startActivity(intent);
			break;
			
		case R.id.avborrow_image_back:
			finish();
			break;

		default:
			break;
		}
	}

}
